package com.its.net.udp.server;

import com.its.common.net.server.impl.UdpServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * @author Xiaxiaopeng
 * @description 功能描述
 * @create 2023/5/31 15:57
 */
@RestController
@RequestMapping("udp")
@ConditionalOnProperty(prefix = "its.net.udp.server", name = "enabled", havingValue = "true")
public class UdpServerEntryPoint {
    @Resource
    UdpServer udpServer;

    @GetMapping("sendOneMsg2All")
    public String sendOneMsg(@RequestParam String msg){
        byte[] body = encodeMessageBody(msg);
        udpServer.sendToAll(body);
        return "Ok";
    }

    @GetMapping("send2One")
    public String send2One(@RequestParam String msg, @RequestParam String serverAddr, @RequestParam int port){
        byte[] body = encodeMessageBody(msg);
        ByteBuf buf = Unpooled.copiedBuffer(body);
        InetSocketAddress addr = new InetSocketAddress(serverAddr,port);
        udpServer.send(addr, buf);
        return "Ok";
    }

    public static byte[] encodeMessageBody(String msg) {
        return msg.getBytes();
    }
}
